package com.dataart.zipbackup;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.dataart.zipbackup.GzipProcessor;
import com.dataart.zipbackup.TextProcessor;

public class ZipProcessor {
	public ZipOutputStream processZip(TextProcessor textProcessor,
			InputStream inputStream, OutputStream outputStream)
			throws IOException {
		ZipInputStream zipInputStream = new ZipInputStream(inputStream); 
		//try{
		//} finally{} Resources must be cleaned up
		//
		ZipEntry zipEntry;
		ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
		while ((zipEntry = zipInputStream.getNextEntry()) != null) {
			String entryName = zipEntry.getName();
			ZipEntry outEntry = new ZipEntry(zipEntry.getName());
			zipOutputStream.putNextEntry(outEntry);
			if (entryName.endsWith(".zip") && !zipEntry.isDirectory()) {
				ZipProcessor newZip = new ZipProcessor();
				ZipOutputStream zos = newZip.processZip(textProcessor,
						zipInputStream, zipOutputStream);
				zos.finish();
			} else if (entryName.endsWith(".gz") && !zipEntry.isDirectory()) {
				GzipProcessor gzipProcessor = new GzipProcessor();
				gzipProcessor.processGzip(entryName, zipInputStream,
						textProcessor, zipOutputStream);
			} else if (entryName.endsWith(".txt") || zipEntry.isDirectory()) {
				textProcessor.processText(zipInputStream, zipOutputStream);
			} else {
				OtherProcessor otherProcessor = new OtherProcessor();
				otherProcessor.pocessOther(zipInputStream, zipOutputStream);
			}
			zipOutputStream.closeEntry();
		}
		return zipOutputStream;
	}
}
